//
//  NSString+Common.m
//  ContinueEducation
//
//  Created by 迟建国 on 2018/7/10.
//  Copyright © 2018年 CE. All rights reserved.
//

#import "NSString+Common.h"
#import <CommonCrypto/CommonDigest.h>
#import "sys/utsname.h"
#include <sys/types.h>
#include <sys/sysctl.h>

@implementation NSString (Common)

- (NSString *)md5Str
{
    if(self == nil || [self length] == 0) return nil;
    unsigned char digest[CC_MD5_DIGEST_LENGTH], i;
    CC_MD5([self UTF8String], (int)[self lengthOfBytesUsingEncoding:NSUTF8StringEncoding], digest);
    NSMutableString *ms = [NSMutableString string];
    for(i=0;i<CC_MD5_DIGEST_LENGTH;i++)
    {
        [ms appendFormat: @"%02x", (int)(digest[i])];
    }
    return [ms copy];
    
}

- (NSString*) sha1Str
{
    const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:self.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (CC_LONG)data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return output;
}

//判断是否是手机号码或者邮箱
- (BOOL)isPhoneNo{
    NSString *phoneRegex = @"1[3|4|5|6|7|8|9|][0-9]{9}|([6|9])[0-9]{7}|09[0-9]{8}|6[6|8][0-9]{5}";
    //    NSString *phoneRegex = @"[0-9]{1,15}";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    
    return [phoneTest evaluateWithObject:self];
}

+ (NSString *)randomNumber:(NSInteger )length{
    
    if (length<=0) {
        return @"000000";
    }
    
    NSString *strRandom = @"";
    
    for(int i=0; i<length; i++)
    {
        strRandom = [strRandom stringByAppendingFormat:@"%i",(arc4random() % 10)];
    }
    return strRandom;
}

- (NSString *)spaceWithNumber:(NSInteger)number{
    if (self.length>0) {
        NSMutableString *preString = [NSMutableString string];
        for (int i=0; i<(self.length+number-1)/number; i++) {
            [preString appendFormat:@"%@ ",[self substringWithRange:NSMakeRange(i*number, MIN(self.length-i*number,number))]];
        }
        return preString;
    }
    return nil;
}

- (NSString *)phoneAddXing{
    if (self.length>7) {
        return [self stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }
    return self;
}

- (BOOL)isPureFloat{
    NSScanner* scan = [NSScanner scannerWithString:self];
    float val;
    
    if ([scan scanFloat:&val] && [scan isAtEnd]) {
        if ([self floatValue]>0) {
            return YES;
        }
    }
    return NO;
}

//检测字符串是否是纯数字
+ (BOOL)isNumber:(NSString *)num
{
    NSString *number = @"0123456789";
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:number] invertedSet];
    NSString *filtered = [[num componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basic = [num isEqualToString:filtered];
    return basic;
}

//检测字符串是否是数字或字母组成
+ (BOOL)isNumberOrLetter:(NSString *)num
{
    NSString *numberOrLetter = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:numberOrLetter] invertedSet];
    NSString *filtered = [[num componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basic = [num isEqualToString:filtered];
    return basic;
}

//检测是否是手机号码
+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    NSString * mobile = @"^1[3456789]\\d{9}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mobile];
    if ([regextestmobile evaluateWithObject:mobileNum] == YES) {
        return YES;
    }else {
        return NO;
    }
}

//判断字符串是否为空或者都是空格
+ (BOOL)isBlankString:(NSString *)string
{
    if (string == nil){
        return YES;
    }
    if (string == NULL){
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]){
        return YES;
    }
    //判断字符串是否全部为空格（[NSCharacterSet whitespaceAndNewlineCharacterSet]去掉字符串两端的空格)
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0){
        return YES;
    }
    return NO;
}



-(BOOL)checkPassWord{
    //6-18位数字和字母组成
    //    NSString *regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$";
    NSString *regex = @"[0-9A-Za-z]{6,18}$";
    
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if ([pred evaluateWithObject:self]) {
        return YES ;
    }else
        return NO;
}

/**
 邮箱格式判断
 
 @param email <#email description#>
 @return <#return value description#>
 */
+(BOOL )isValidateEmail:( NSString  *)email
{
    
    NSString  *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" ;
    
    NSPredicate  *emailTest = [ NSPredicate   predicateWithFormat : @"SELF MATCHES%@",emailRegex];
    
    return  [emailTest  evaluateWithObject :email];
    
}

//将0123456789转化为ABCDEFGHIJKLMN
+ (NSString *)exchangeNumToABC:(NSInteger)index{
    NSString *str = nil;
    switch (index) {
        case 0:
        {
            str = @"A";
        }
            break;
        case 1:
        {
            str = @"B";
        }
            break;
        case 2:
        {
            str = @"C";
        }
            break;
        case 3:
        {
            str = @"D";
        }
            break;
        case 4:
        {
            str = @"E";
        }
            break;
        case 5:
        {
            str = @"F";
        }
            break;
        case 6:
        {
            str = @"G";
        }
            break;
        case 7:
        {
            str = @"H";
        }
            break;
        case 8:
        {
            str = @"I";
        }
            break;
            
        default:
            break;
    }
    return str;
}
//将ABCDEFGHIJKLMN转化为0123456789
+ (NSInteger)exchangeABCToNum:(NSString *)str{
    NSInteger index = 0;
    if ([str isEqualToString:@"A"]) {
        index = 0;
    }
    if ([str isEqualToString:@"B"]) {
        index = 1;
    }
    if ([str isEqualToString:@"C"]) {
        index = 2;
    }
    if ([str isEqualToString:@"D"]) {
        index = 3;
    }
    if ([str isEqualToString:@"E"]) {
        index = 4;
    }
    if ([str isEqualToString:@"F"]) {
        index = 5;
    }
    if ([str isEqualToString:@"G"]) {
        index = 6;
    }
    if ([str isEqualToString:@"H"]) {
        index = 7;
    }
    if ([str isEqualToString:@"I"]) {
        index = 8;
    }
    return index;
}


//将字符串按数字正向排序返回新的字符串
+ (NSString *)sortStringWith:(NSString *)str{
    NSString *newStr = @"";
    NSArray *strArr = [str componentsSeparatedByString:@","];
    NSArray *newArr = [strArr sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2];
    }];
    NSLog(@"%@", newArr);
    newStr = [newArr componentsJoinedByString:@","];
    
    return newStr;
}

+(NSString *)filterHTMLImage:(NSString *)str{
    NSScanner * scanner = [NSScanner scannerWithString:str];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<img" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        str  =  [str  stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@"【图片】"];
    }
    return str;
}

+ (NSString *)filterHTMLTag:(NSString *)str {
    //替换字符
    str  =  [str  stringByReplacingOccurrencesOfString:@"&mdash;" withString:@"-"];
    str  =  [str  stringByReplacingOccurrencesOfString:@"&ldquo;" withString:@"\""];
    str  =  [str  stringByReplacingOccurrencesOfString:@"&rdquo;" withString:@"\""];
    str  =  [str  stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
    str  =  [str  stringByReplacingOccurrencesOfString:@"&rsquo;" withString:@"’"];
    str  =  [str  stringByReplacingOccurrencesOfString:@"&lsquo;" withString:@"‘"];
    str  =  [str  stringByReplacingOccurrencesOfString:@"&middot;" withString:@"·"];
    str  =  [str  stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    str  =  [str  stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
    str  =  [str  stringByReplacingOccurrencesOfString:@"<strong>" withString:@""];
    str  =  [str  stringByReplacingOccurrencesOfString:@"</strong>" withString:@""];
    str  =  [str  stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
    return str;
}

+(NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

-(NSString *)getZZwithString:(NSString *)string{
    NSRegularExpression *regularExpretion=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|\n|&nbsp;"
                                                                                    options:0
                                                                                      error:nil];
    string=[regularExpretion stringByReplacingMatchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, string.length) withTemplate:@""];
    return string;
}

+ (CGSize)getStringSizeWith:(NSString *)str boundingRectWithSize:(CGSize)size strFont:(CGFloat)fontsize{
    return [str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontsize]} context:nil].size;
}

#pragma mark - 将某个时间转化成 时间戳
+ (NSInteger)timeSwitchTimestamp:(NSString *)formatTime andFormatter:(NSString *)format{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format]; //(@"YYYY-MM-dd hh:mm:ss") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate* date = [formatter dateFromString:formatTime]; //------------将字符串按formatter转成nsdate
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    return timeSp;
    
}

#pragma mark - 将某个时间戳转化成 时间
+ (NSString *)timestampSwitchTime:(NSInteger)timestamp andFormatter:(NSString *)format{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format]; // （@"YYYY-MM-dd hh:mm:ss"）----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
    
}

+(NSString *)stringWithFilterStr:(NSString *)fliterStr{
    NSString *str = [NSString stringWithFormat:@"%@", fliterStr];
    if ([str isEqualToString:@"0"]) {
        return @"A";
    }
    if ([str isEqualToString:@"1"]) {
        return @"B";
    }
    if ([str isEqualToString:@"2"]) {
        return @"C";
    }
    if ([str isEqualToString:@"3"]) {
        return @"D";
    }
    if ([str isEqualToString:@"4"]) {
        return @"E";
    }
    if ([str isEqualToString:@"5"]) {
        return @"F";
    }
    return @"";
}
/**
 秒数转固定格式的时间字符串
 
 @param time 秒数
 @return 时间字符串
 */
+(NSString *)timeFormat:(NSInteger)time {
    NSInteger minutes = time / 60;
    NSInteger seconds = time % 60;
    NSString *timeStr = [NSString stringWithFormat:@"%02d:%02d",(int)minutes,(int)seconds];
    return timeStr;
}

+ (NSString *)compareWithVersionStoreVersion:(NSString *)storeVersion OnLineVersion:(NSString *)onLineVersion{
    NSArray *storeVersionArr = [storeVersion componentsSeparatedByString:@"."];
    NSArray *onLineVersionArr = [onLineVersion componentsSeparatedByString:@"."];
    NSString *version = storeVersion;
    for (int i = 0; i < onLineVersionArr.count; i++) {
        NSInteger onLineItem = [[onLineVersionArr objectAtIndex:i] integerValue];
        NSInteger storeItem = [[storeVersionArr objectAtIndex:i] integerValue];
        
        if (onLineItem < storeItem) {
            version = storeVersion;
            break;
        }
        if (storeItem < onLineItem) {
            version = onLineVersion;
            break;
        }
        
    }
    
    return version;
}

+(NSString*)getCurrentTimes{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    //现在时间,你可以输出来看下是什么格式
    NSDate *datenow = [NSDate date];
    //----------将nsdate按formatter格式转成nsstring
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    return currentTimeString;
}

+(BOOL)checkProductDate:(NSString *)tempDate {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:tempDate];
    
//    NSString *beginTimeStr = [dateFormatter stringFromDate:date];
    
    // 判断是否大于当前时间
    if ([date earlierDate:[NSDate date]] != date) {
        return YES;
    } else {
        return NO;
    }
    
}

+ (NSTimeInterval)getTimeFromBeginTime:(NSString *)beginTime endTime:(NSString *)endTime {
    NSDateFormatter *beginDateFormatter = [[NSDateFormatter alloc] init];
    [beginDateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [beginDateFormatter setTimeZone:timeZone];
    NSDate *beginDate = [beginDateFormatter dateFromString:beginTime];
    
//    NSString *beginTimeStr = [beginDateFormatter stringFromDate:beginDate];
    
    NSDateFormatter *enddateFormatter = [[NSDateFormatter alloc] init];
    [enddateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSTimeZone* endtimeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [enddateFormatter setTimeZone:endtimeZone];
    NSDate *enddate = [enddateFormatter dateFromString:endTime];
    
//    NSString *endTimeStr = [enddateFormatter stringFromDate:enddate];
    
    NSTimeInterval time = [enddate timeIntervalSinceDate:beginDate];
    
    return time;
}

+ (NSTimeInterval)getTimeWith:(NSString *)timeStr {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [dateFormatter setTimeZone:timeZone];
    NSDate *date = [dateFormatter dateFromString:timeStr];
    
    NSDate *datenow = [NSDate date];
    
    NSTimeInterval time = [date timeIntervalSinceDate:datenow];
    
    return time;
}

+ (NSString *)secondsToHourMinuteFormat:(int)totalSeconds {
    int minutes = totalSeconds / 60;
    int second = totalSeconds % 60;
    NSString *format = [NSString stringWithFormat:@"%02d:%02d", minutes, second];
    return format;
}
@end
